/*
** creation.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Tue Jul  5 10:00:15 2011 michael guidet
** Last update Tue Jul  5 10:14:22 2011 michael guidet
*/

#include "server.h"

void			set_default(t_env *e)
{
  srand(time(NULL));
  e->time_pop = (long)(70.0f / (float)e->t * 1000000.0f);
  e->port = PORT;
  e->width = WIDTH;
  e->height = HEIGHT;
  e->max_connect = MAX_CONNECT;
  e->t = TIME;
  e->teams = NULL;
  e->fd = NULL;
  e->new_id = 1;
  FD_ZERO(&e->fd_read);
  FD_ZERO(&e->fd_write);
  e->max = 0;
}

void			create_player_for_team(t_env *e)
{
  int			i;
  int			j;
  t_player		*drone;

  for (i = 0; e->teams[i].name != NULL; i++)
    for (j = 0; j < e->max_connect; j++)
      {
	drone = new_drone(e->teams[i].name, rand() % e->width,
			  rand() % e->height, e->t);
	drone->id = e->new_id;
	e->new_id++;
	add_drone_to_team(&(e->teams[i]), drone);
	e->teams[i].dispo++;
      }
}

void			create_server(t_env *e)
{
  int			s;
  struct sockaddr_in	sin;
  struct protoent	*pe;
  t_fd			*new_elem;

  pe = x_null(NULL, getprotobyname("tcp"), "getprotobyname");
  s = x_int(-1, socket(PF_INET, SOCK_STREAM, pe->p_proto), "socket");
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = INADDR_ANY;
  sin.sin_port = htons(e->port);
  x_int(-1, bind(s, (struct sockaddr*)&sin, sizeof(sin)), "bind");
  x_int(-1, listen(s, MAX_CLIENT), "listen");
  new_elem = x_null(NULL, malloc(sizeof(*new_elem)), "malloc");
  new_elem->fd = s;
  new_elem->type = SERV;
  memset(new_elem->buf_read, 0, BUF_SIZE + 1);
  memset(new_elem->buf_write, 0, BUF_SIZE + 1);
  new_elem->next = NULL;
  new_elem->pl = NULL;
  e->fd = new_elem;
  create_player_for_team(e);
}
